package com.cdc.servlet.fileupload;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
 * location：表示文件存储的位置。默认为当前文件工作运行路径。 maxFileSize：允许上传的文件最大值(单位为字节)，默认为-1，表示没有限制。
 * maxRequestSize：针对该mulitpart/from-data请求的最大值(单位为字节)，默认为-1.
 * fileSizeThread：当数据量大于该值时，内容将被写入文件。
 * 
 * @author admin
 *location = "/upload",
 */
@WebServlet("/FileUploadServlet")
@MultipartConfig( location = "E://upload",maxFileSize = -1, maxRequestSize = -1, fileSizeThreshold = 1)
public class SingleFileUploadServlet extends HttpServlet {
	private static final long serialVersionUID = -3306115360706905461L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //拿到请求的part部件
        Part part = request.getPart("filename");
        String disposition = part.getHeader("content-disposition");
        System.out.println("disposition：" + disposition);
        // 获取上传的文件名
		String nameS = part.getSubmittedFileName();
        System.out.println("文件名称：" + nameS);
		String pathS = request.getSession().getServletContext().getRealPath("/") + "upload\\";
		System.out.println("文件路径：" + pathS);
        //截取到文件名的后缀
        String suffix = nameS.substring(nameS.lastIndexOf("."));
        System.out.println("文件后缀：" + suffix);
        //随机生成一个UUID
        String uuid = UUID.randomUUID().toString();
        //保存到pathS目录下
        part.write(pathS + nameS+"_"+uuid + suffix);
        request.setAttribute("msg", disposition+pathS + nameS+"_"+uuid + suffix);
        request.getRequestDispatcher("servlet/uploadfile/uploadFile.jsp").forward(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}
